package spring.bean_init;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import javax.annotation.PostConstruct;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

public class LearnBeanInit {
    public static void main(String[] args) throws Exception {
        ApplicationContext context = new AnnotationConfigApplicationContext(LearnConfig.class);
        LearnBeanService bean = context.getBean(LearnBeanService.class);
        System.out.println("使用中——context获取到bean对象：" + bean);
        bean.destroy();
        System.out.println("---------------------------------");
    }
}

// 配置类，扫描组件
@Configuration
@ComponentScan(basePackages = "spring.bean_init") // 假设你的类在 spring 包下
class LearnConfig {
    // 在配置类里加@Bean注解的方式注册bean，可以声明bean的一个initMethod
    @Bean(initMethod = "initMethod")
    public LearnBeanService learnBeanService() {
        return new LearnBeanService();
    }
}

@Component
class LearnBeanService implements InitializingBean, BeanNameAware, DisposableBean {
    String beanName;

    @Override
    public String toString() {
        return "LearnBeanService";
    }

    @Override
    public void setBeanName(String name) {
        beanName = name;
        System.out.println("初始化——执行BeanNameAware接口的setBeanName方法");
    }

    @PostConstruct
    public void init() {
        System.out.println("初始化——执行被@PostConstruct注解的初始化方法");
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("初始化——执行InitializingBean接口的afterPropertiesSet方法");
    }

    public void initMethod() {
        System.out.println("初始化——执行initMethod方法");
    }

    @Override
    public void destroy() throws Exception {
        System.out.println("销毁——执行DisposableBean接口的destroy方法");
    }
}

// 对所有其他的Bean在初始化前后做增强处理
@Component
class learnPostProcessor implements BeanPostProcessor {
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        System.out.println("初始化前——执行LogPostProcessor的BeforeInitialization: " + beanName);
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        System.out.println("初始化后——执行LogPostProcessor的AfterInitialization: " + beanName);
        return bean;
    }
}
